#ifndef THREADPOOLIMP_H_MYIDENTIFY_1985
#define THREADPOOLIMP_H_MYIDENTIFY_1985

#include "lock.hpp"
#include "condition.hpp"
#include "multitimer.hpp"
#include <pthread.h>
#include <deque>
#include <vector>
#include <stdio.h>
#include <boost/function.hpp>
//the max timers can exist at the same time. 
#ifndef THREAD_POOL_MAX_TIMER
#define THREAD_POOL_MAX_TIMER 16
#endif

namespace threadpool
{
    typedef boost::function<void()> task_type;
    class threadpoolimp
    {
    public:
        threadpoolimp()
            :m_terminateall(false),
            m_timertask_container(THREAD_POOL_MAX_TIMER)
        {
        }
        ~threadpoolimp()
        {
        }

        void terminateall()
        {
            m_terminateall = true;
        }
        inline bool getterminate()
        {
            return m_terminateall;
        }
        void push_task(const task_type& task)
        {
            m_task_container.push_back(task);
        }
        task_type& top_task()
        {
            return m_task_container.front();
        }
        void pop_task()
        {
            m_task_container.pop_front();
        }
        inline bool taskempty()
        {
            return m_task_container.empty();
        }
        //void notifyone_worker_idle_event()
        //{
        //    m_worker_idle_event.notify_one();
        //}
        //void notifyall_worker_idle_event()
        //{
        //    m_worker_idle_event.notify_all();
        //}
        void notifyone_task_coming_event()
        {
            m_task_coming_event.notify_one();
        }
        void notifyall_task_coming_event()
        {
            m_task_coming_event.notify_all();
        }
        //void wait_worker_idle_event()
        //{
        //    m_worker_idle_event.wait(m_locker);
        //}
        void wait_task_coming_event()
        {
            m_task_coming_event.wait(m_locker);
        }
        void push_thread(pthread_t pid)
        {
            if(pid)
                m_pids.push_back(pid);
        }
        bool threadempty()
        {
            return m_pids.empty();
        }
        void waittoterminate()
        {
            for(size_t i=0;i<m_pids.size();i++)
            {
                pthread_join(m_pids[i],NULL);
            }
            printf("wait all thread joined success.\n");
        }

        void clearalltask()
        {
            m_task_container.clear();
            m_timertask_container.clear();
        }
        bool m_terminateall;
        wwcore::common::locker m_locker;
        //condition m_worker_idle_event;
        wwcore::common::condition m_task_coming_event;
        std::deque<task_type> m_task_container;
        std::vector<pthread_t> m_pids;
        std::vector<multitimer> m_timertask_container;
    };
}

#endif
